//
//  UINavigationBar+Awesome.m
//  LTNavigationBar
//
//  Created by ltebean on 15-2-15.
//  Copyright (c) 2015 ltebean. All rights reserved.
//

#import "UINavigationBar+Awesome.h"
#import <objc/runtime.h>

#define TAG_LINE            100001

@implementation UINavigationBar (Awesome)
static char overlayKey;

- (UIView *)overlay {
    return objc_getAssociatedObject(self, &overlayKey);
}

- (void)setOverlay:(UIView *)overlay {
    objc_setAssociatedObject(self, &overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)lt_setBackgroundColor:(UIColor *)backgroundColor {
    CGRect overlayFrame = CGRectMake(0, -20, [UIScreen mainScreen].bounds.size.width, CGRectGetHeight(self.bounds) + 20);
    CGRect lineFrame = CGRectMake(0, CGRectGetHeight(overlayFrame) - SUIT_LINE_WIDTH, CGRectGetWidth(overlayFrame), SUIT_LINE_WIDTH);
    if (!self.overlay) {
        for (UIView *v in self.subviews) {
            if ([v isKindOfClass:[UIImageView class]]) {
                v.hidden = YES;
            }
        }
        self.overlay = [[UIView alloc] initWithFrame:overlayFrame];
        self.overlay.userInteractionEnabled = NO;
        self.overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [self insertSubview:self.overlay atIndex:0];


        // 添加下划线
        UIView *line = [[UIView alloc] initWithFrame:lineFrame];
        line.tag = TAG_LINE;
        line.backgroundColor = UI_COLOR_LINE_GREY;
        line.layer.opacity = 0.f;
        [self.overlay addSubview:line];
    }
    self.overlay.frame = overlayFrame;
    self.overlay.backgroundColor = backgroundColor;
    UIView *line = [self.overlay viewWithTag:TAG_LINE];
    line.frame = lineFrame;
    CGFloat alpha = CGColorGetComponents(backgroundColor.CGColor)[3];
    if (alpha >= 0.99f && alpha <= 1.01f) {
        line.layer.opacity = 1.f;
    } else {
        line.layer.opacity = 0.f;
    }
}

- (void)lt_setTranslationY:(CGFloat)translationY {
    self.transform = CGAffineTransformMakeTranslation(0, translationY);
}

- (void)lt_setElementsAlpha:(CGFloat)alpha {
    [[self valueForKey:@"_leftViews"] enumerateObjectsUsingBlock:^(UIView *view, NSUInteger i, BOOL *stop) {
        view.alpha = alpha;
    }];

    [[self valueForKey:@"_rightViews"] enumerateObjectsUsingBlock:^(UIView *view, NSUInteger i, BOOL *stop) {
        view.alpha = alpha;
    }];

    UIView *titleView = [self valueForKey:@"_titleView"];
    titleView.alpha = alpha;
}

- (void)lt_reset {
    [self setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.overlay removeFromSuperview];
    self.overlay = nil;
}

@end
// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com